package Server;

import java.util.*;
import java.io.*;

/**
 * Concrete Mediator
 * clientList connected to the server
 * @author Yaxing Chen
 *
 */
class ClientMediator implements Mediator{
	private ArrayList<ClientSocket> list;
	private int nextUserId = 0;
	
	public ArrayList<ClientSocket> getList(){
		if(list == null){
			list = new ArrayList<ClientSocket>();
		}
		return list;
	}
	
	public void newClient(ClientSocket newClient){
		getList();
		list.add(newClient);
		nextUserId ++;
	}
	
	public boolean removeClient(int id){
		if(getList().isEmpty()){
			return false;
		}
		for(ClientSocket e : list){
			if(e.getId() == id){
				list.remove(e);
				break;
			}
		}
		nextUserId --;
		return true;
	}
	
	public int getNewUserId(){
		if(list == null){
			getList();
			nextUserId = 0;
		}
		return getList().size();
	}
	
	public int getUserQty(){
		if(list == null){
			getList();
		}
		return list.size();
	}
	
	/**
	 * when new client connected, dispatch a new ID
	 * @param id
	 * @return true/false
	 */
	public boolean assignClientID(int id){
		try{
			for(ClientSocket e : this.getList()){
	          	if(e.getId() == id){
	          		e.getOutputStream().writeUTF(Integer.toString(id));
	          		break;
	         	}
	       	}
		}catch(IOException e){
			return false;
		}
		return true;
	}
	
	/**
	 * send message to all colleague
	 * @param senderID
	 * @param content
	 * @return
	 */
	public boolean sendToAll(int senderId, String content){
		try{
			for(ClientSocket e : this.getList()){
	           	if(e.getId() == senderId){
	           		continue;
	           	}
	           	e.getOutputStream().writeUTF(content);
	        }
		}catch(IOException e){
			return false;
		}
		return true;
	} 
}